<template>
	<view class="shoppingcart">

		<!-- 选择收货地址 --> 
		<view class="address">
			<!-- 默认 -->
			<view class="default-address" @click="changAddress()">
				<view class="left">
					<text class="iconfont">&#xe64b;</text>
				</view>
				<view class="right">
					<view class="list-1" v-if="is_exist">
						<text class="name">收货人： {{address.name}}</text>
						<text class="num">{{address.phone}}</text>
					</view>
					<view class="list-2" v-if="is_exist">
						{{address.province + address.city + address.district + address.address}}
					</view>
					<view class="list-2" v-else>
						您还没有添加地址，点击这里添加。。
					</view>
					<view class="list-3" v-if="address.is_default == 0">
						默认
					</view>
					<view class="list-4">
						<text class="iconfont">&#xe708;</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 购物车中商品的每项 -->
		<view class="shopCt-item" v-for="(shop,index) in shopCart" :key="index" v-show="shopCart.length != 0">
			<!-- 顶部 -->
			<view class="it-title">
				<view class="tt-line1">
					<radio value="shop" :checked="shop.shopSelect" @click="shopSelect(shop.shop_id,shop.shopSelect)" color="#ff557d" />
				</view>
				<view class="tt-line2" @click="navTo(`/pages/user/storedetails?shid=${shop.shopid}`)">
					{{shop.shop_name}} <text class="iconfont">&#xe600;</text>
				</view>
				<view class="tt-line1">
					<view class="btn-del">
						<text>删除</text>
					</view>
					<!-- <button size="mini" type="default" @click="del(shop.shop_id)">删除</button> -->
				</view>
			</view>

			<!-- 店铺内的商品每一项 -->
			<view class="it-container" v-for="(goods,sub) in shop.itemInfo" :key="sub">
				<view class="it-content" >
					<view class="tt-line1">
						<radio value="goods" :checked="goods.goodsSelect" @click="goodsSelect(shop.shop_id ,goods)" style="transform: scale(0.7);"
						 color="#ff557d" />
					</view>
				
					<view class="tt-line2">
						<view class="l2-1">
							<image :src="goods.product_img" mode="aspectFill"></image>
							<view class="title">
								<text>{{goods.product_name}}</text>
				
								<view class="ab">
									<text>￥{{goods.product_price}}</text>
									<tui-numberbox v-model="goods.product_quantity" :max="goods.pronums" @change="change($event, shop.shop_id, goods.product_id)"
									 class="number-box"></tui-numberbox>
								</view>
							</view>
						</view>
					</view>
					
				</view>
				
				<view class="yh-price" v-if="goods.addgift == 1">
					已享受满减，优惠<text>6.9</text> 元
				</view>
			</view>
			
			
			<!-- 配送方式 -->
			<view class="ps-pattern">
				<text>配送方式：</text>
				<text @click="onExpress(shop)">
					{{shop.delivery_name}}
					<text class="iconfont" style="font-size: 20upx;">&#xe600;</text>
				</text>
			</view>

			<view class="item-pay">
				<text class="count-num">共{{ totalPrice[7][shop.shop_id] }}件商品</text>
				<text class="count-price">
					合计:
					<text>￥ {{ totalPrice[6][shop.shop_id] }}</text>
				</text>
			</view>
		</view>

		<view class="qs" v-show="shopCart.length == 0">
			您还没有商品加入到购物车
		</view>

		<!-- <view class="shopCt-item">
			<view class="it-title">
				<view class="tt-line1">
					<text class="iconfont" style="color: #ccc;" v-if="selectFlag">&#xe601;</text>
					<text class="iconfont" style="color: #de5c8a;" v-else>&#xe63b;</text>
				</view>
				<view class="tt-line2">
					瑞派宠物店 <text class="iconfont">&#xe600;</text>
				</view>
				<view class="tt-line1">
					<button size="mini" type="default" @click="del()">删除</button>
				</view>
			</view>
			<view class="it-content">
				<view class="tt-line1">
					<text class="iconfont" style="color: #ccc;" v-if="!selectFlag">&#xe601;</text>
					<text class="iconfont" style="color: #de5c8a;" v-else>&#xe63b;</text>
				</view>

				<view class="tt-line2">
					<view class="l2-1">
						<image src="../../static/imgs/dt-image1.png" mode=""></image>
						<view class="title">
							<text>皇家猫粮室内专用10kg，满50送储粮桶</text>

							<view class="ab">
								<text>￥9.9</text>
								<tui-numberbox :value="value" :max="10" @change="change" class="number-box"></tui-numberbox>
							</view>
						</view>
					</view>

					<view class="yh-price">
						已享受秒杀，优惠<text>6.9</text> 元
					</view>
					<view class="ps-pattern">
						<text>配送方式：</text>
						<text>免费包邮 <text class="iconfont" style="font-size: 20upx;">&#xe600;</text></text>
					</view>
				</view>

			</view>

			<view class="it-content">
				<view class="tt-line1">
					<text class="iconfont" style="color: #ccc;" v-if="!selectFlag">&#xe601;</text>
					<text class="iconfont" style="color: #de5c8a;" v-else>&#xe63b;</text>
				</view>

				<view class="tt-line2">
					<view class="l2-1">
						<image src="../../static/imgs/dt-image1.png" mode=""></image>
						<view class="title">
							<text>皇家猫粮室内专用10kg，满50送储粮桶</text>

							<view class="ab">
								<text>￥9.9</text>
								<tui-numberbox :value="value" :max="10" @change="change" class="number-box"></tui-numberbox>
							</view>
						</view>
					</view>

					<view class="yh-price">
						已享受秒杀，优惠<text>6.9</text> 元
					</view>

					<view class="ps-pattern">
						<text>配送方式：</text>
						<text>免费包邮 <text class="iconfont" style="font-size: 20upx;">&#xe600;</text></text>
					</view>

				</view>

			</view>

			<view class="item-pay">
				<text class="count-num">共1件商品</text>
				<text class="count-price">合计:<text>￥9999.9</text></text>

			</view>

		</view>
 -->


		<!-- 最底部的结算区域 -->
		<view class="footer-buy">
			<view class="area1">
				<radio value="shop" :checked="allFlag" @click="onAll(allFlag)" color="#ff557d" />
				<text class="checkAll">全选</text>
			</view>

			<view class="area1">
				<view class="heji">
					合计：<text>￥{{ totalPrice[6] | comput  }}</text>
				</view>

			</view>

			<view class="area1">
				<view class="settlement-btn" @click="pay1()">
					<text>结算</text>
				</view>
				<!-- <button type="default" size="mini" @click="pay1()">结算</button> -->
			</view>
		</view>

	</view>
</template>

<script>
	import tuiNumberbox from "@/components/numberbox/numberbox";
	import {
		mapState,
		mapMutations,
		mapGetters
	} from "vuex";
	export default {
		components: {
			tuiNumberbox
		},
		data() {
			return {
				key: "value",
				numberText: 1,
				selectFlag: false,
				value: 1,
				shopFlag: true,
				goodsFlag: true,
				totalList: {}, // 所有的
				discountList: {}, // 减的价格
				shopCart1: [], // 购物车数据
				is_exist: true, // 判断是否有地址
				address: {},
				// allFlag: false, // 全选
				// delData: [],
			}
		},
		computed: {
			...mapState(['shopCart', 'payData','delData','allFlag']),
			...mapGetters(['totalPrice']),
			

		},
		onLoad() {
			this.getCateData();
			
		},
		onShow() {
			let token = uni.getStorageSync('lph-token') || '';
			if(token) {
					console.log(1);
					this.judgeAddress();
			}
			
		},
		filters: {
			comput: (val) => {
				var total = 0;
				for (var i in val) {
					total =  (total * 10000 + val[i] * 10000) / 10000;
				}
				return total;
			}
		},
		
		watch: {
			totalPrice: {
				handler(newVal, oldVal) {
					// newVal
					console.log(newVal);
					this.shopCart.forEach((shop) => {
						let sNum = newVal[1][shop.shop_id]
						console.log(sNum);
						// if()
						
					})
					// console.log(newVal);
					// this.calcTotal();
					// this.delData = this.shopCart;
				},
				deep: true
			}
		},
		methods: {
			...mapMutations([
				'addCart',
				'updateNum',
				'updateAddress',
				'updataSelect',
				'delStoreGoods',
				'updateCart',
				'changePayData',
				'delGoods',
				'xshopSelect', // 店铺的勾选
				'allSelectS', // 底部的全选
				
			]),
			async pay1() { // 点击结算
				let temp = [];
				this.shopCart.forEach((item, index) => { // 每个店铺的
					let products = [];
					if (this.totalPrice[2][item.shop_id] != 0) { // 判断店铺是否选择
						item.itemInfo.some(childItem => { // 店铺内每件商品是数据 2
							if (childItem.goodsSelect === true) { // 商品是否选择 2个都选
								products.push({
									products_id: childItem.product_id,
									distype: 1,
									quantity: childItem.product_quantity,
								})
							}
						})
						temp.push({
							shop_id: item.shop_id,
							price: this.totalPrice[2][item.shop_id],
							discount: this.totalPrice[3][item.shop_id],
							delivery_type: item.delivery_type,
							order_comment: item.comment,
							products: products
						})
					}
				});
				if (temp.length != 0) {
					let total = 0; // 支付总价
					for (let i in this.totalPrice[2]) {
						total += this.totalPrice[2][i]
					}
					let sendData = {
						action: 'create_order',
						pay_amount: total,
						pay_type: 2,
						user_address_id: this.address.addressid,
						products_data: temp,
					}
					// console.log(sendData);
					this.changePayData(sendData)
					uni.navigateTo({
						url: `/pages/discountMall/cartPay`
					})
				} else {
					uni.showToast({
						title: '请选择商品后再结算~~',
						icon: 'none'
					})
				}

			},
			onAll(a) { // 全选
				this.allSelectS(!a)
			},
			async judgeAddress() { // 地址的判断
				// 1. 后台传过来地址
				// 2. 点击更换，使用缓存中的地址
				// 3. 两个地址都有的情况下，优先使用哪一个？
				let addressStore = uni.getStorageSync('lph-address');
				if ('addressid' in addressStore) {
					this.is_exist = true;
					this.address = addressStore;
					return
				}
				let a = await this.$http.getShipAddress();
				if (a.code == 404) { //  没有添加过地址的清空判断
					this.is_exist = false;
					return;
				}
				this.is_exist = true;
				this.address = a.data[0];
			},
			changAddress() { // 更换收货地址
				uni.navigateTo({
					url: '/pages/set/shipAddress?position=1'
				})
			},
			async getCateData() { // 购物车数据
				let result = await this.$http.getCateData();
				if (result.code == 200) {
					this.updateCart(result.data);
					return
				}
				uni.showToast({
					title: '购物车获取失败，请刷新~~',
					icon: 'none'
				})
			},
			shopSelect(shop_id,selected) { // 勾选店铺
				let zzz = selected;
				console.log(zzz);
				let a = {
					shop_id: shop_id,
					selected: !selected
				}
				console.log(a);
				this.xshopSelect(a);
				
			},
			calcTotal() {
				return
				this.shopCart.forEach((item, index) => {
					let total = 0;
					item.itemInfo.forEach(goods => {
						if (goods.goodsSelected) {
							total += Math.abs(goods.num * parseFloat(goods.price))
						}
					})
					if (typeof item.benefit != 'number') {
						let benefit = JSON.parse(JSON.stringify(item.benefit));
						benefit.reverse();
						for (let i = 0; i < benefit.length; i++) {
							if (total >= parseFloat(benefit[i].amout_srtart)) {
								let discount = parseFloat(benefit[i].discount)
								total -= discount
								this.discountList[item.shopid] = discount
								break;
							} else {
								this.discountList[item.shopid] = 0
							}
						}
					}
					this.totalList[item.shopid] = total

				})
			},
			goodsSelect(shop_id, goods) { // 商品选择变更
				let u = {
					shop_id: shop_id,
					product_id: goods.product_id,
					goodsSelect: !goods.goodsSelect
				}
				this.updataSelect(u);
			},
			change(e, shop_id, product_id) { // 数量选择 
				let u = {
					shop_id: shop_id,
					product_id: product_id,
					product_quantity: e.value
				}
				this.updateNum(u);
			},
			onExpress(shop) { // 选择送货方式
				let list = ['自提', '送货上门'];
				uni.showActionSheet({
					itemList: list,
					success: (res) => {
						let id = res.tapIndex + 1;
						let u = {
							shop_id: shop.shop_id,
							delivery_name: list[res.tapIndex],
							delivery_type: id
						}
						this.updateAddress(u);

					}
				})
			},
			del(shop_id) { // 删除当前店铺的所有商品
				// 1.删除单个商品
				// 2.删除全部商品 - 删除掉店铺
				// 数据格式
					let a = [{
							shopid: 1,
							goodsId: [1, 2],
						},
						{
							shopid: 1,
							goodsId: 2
						},
					]
			
				uni.showModal({
					content: '是否要删除此店铺内的商品~~',
					success: (res) => {
						if (res.confirm) {
							let delData1 = {
								shop_id: shop_id,
								totalPrice: this.totalPrice[7],
							}

							this.delStoreGoods(delData1);
							
							if(this.delData.goodsId.length > 0) {
								console.log(this.delData);
								
								this.$http.deleteShoppingCart(this.delData).then((data) => {
									
									
									if(data.code == 200 ) {
										setTimeout(() => {
											this.getCateData();
										},500);
										uni.showToast({
											title: '当前勾选商品已删除~~',
											icon: 'none'
										})
										return
									}
									uni.showToast({
										title: '删除失败，请重试~~',
										icon: 'none'
									})
								})
								return
							}
							uni.showToast({
								title: '请勾选删除商品~~',
								icon: 'none'
							})
							
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				});

			},
			// 路由跳转
			navTo(url) {
				uni.navigateTo({
					url
				})
			},

		},

	}
</script>

<style lang="scss" scoped>
	@import 'static/css/smallCommon.scss';
	@import 'static/css/ticket.scss';

	// 调整数字输入框的样式
	.uni-numbox {}

	.numberBox {
		// width: 152upx;
		// height: 40upx;
		// line-height: 40upx;
		opacity: 0.7;
		float: right;

		.uni-numbox__value {
			line-height: 30upx;
		}
	}

	// 弹窗部分样式的处理
</style>
